package com.briup.ch11;

import java.io.*;

/**
 * @Author briup-adam
 * @Date 2023/10/23 下午2:37
 * @Description
 * @see java.io.ObjectOutputStream
 * @see  java.io.ObjectInputStream
 *
 **/

public class ReadAndWriteObject {
    /**
     * 将具体对象写的文件中去
     * @param t  对象流要传输的对象
     * @param path  输出的文件路径
     * @param <T>  对象类型
     */
    public  static<T>  void writeObject(T t,String path) throws IOException {
        FileOutputStream fos=null;
        ObjectOutputStream oos=null;

        fos=new FileOutputStream(path);
        oos=new ObjectOutputStream(fos);

        oos.writeObject(t);

        if (oos!=null)
            oos.close();
        if (fos!=null)
            fos.close();
    }

    public static <T> T    readObject(String path) throws IOException, ClassNotFoundException {
        FileInputStream fis=null;
        ObjectInputStream ois=null;

        fis=new FileInputStream(path);
        ois=new ObjectInputStream(fis);

        T o = (T) ois.readObject();


        if (ois!=null){
            ois.close();
        }
        if (fis!=null)
            fis.close();
        return o;

    }

    public static void main(String[] args) {
        Student stu = new Student("海鹏", 30,"123456");
        System.out.println("stu.getPassword() = " + stu.getPassword());
        try {
//            writeObject(stu,"02code/src/stu.txt");

            //反序列化操作会重建对象  但是不会调用构造器
            Student o = readObject("02code/src/stu.txt");
            System.out.println(o);

            System.out.println(stu==o);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
